//
//  WhzPDDSearchViewController.m
//  WhzPinDuoDuo
//
//  Created by whz on 16/11/13.
//  Copyright © 2016年 whz. All rights reserved.
//

// http://api-static.yangkeduo.com/operations 搜索链接

#import "WhzPDDSearchViewController.h"
#import "WhzPDDSearchCategoryCell.h"
#import "WhzPDDSearchGoodsCell.h"
#import "WhzPDDSearchCollectionReusableView.h"
#import "WhzPDDRootModel.h"
#import "WhzPDDChildrenModel.h"
#import "WhzPDDFlowLayout.h"
#import "NetworkTool.h"
#import <YYModel.h>
#import <Masonry.h>

#define KCELLCATEGORY @"cellCategory"
#define KCELLGOODS @"cellGoods"
#define KREUSABLEVIEW @"reusableView"

@interface WhzPDDSearchViewController () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

/**
 搜索商品预留视图
 */
@property(nonatomic, strong)UIView *viewSearch;
/**
 左侧商品分类视图
 */
@property(nonatomic, strong)UITableView *tableViewCategory;
/**
 右侧商品视图
 */
@property(nonatomic, strong)UICollectionView *collectionViewGoods;

@end

@implementation WhzPDDSearchViewController
{
    // 接收网络获取到的数据的数组
    NSArray *_arrayRootData;
    // 接收网络获取到的数据的模型
    NSArray *_arrayRoodModel;
    // 是否是向下拖动
    BOOL _isScrollDown;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化UI
    [self setupUI];
    
    // 获取网络数据
    [self loadNetworkData];
}

#pragma mark - 初始化UI
/**
 初始化UI
 */
- (void)setupUI {
    
    CGFloat navigationBarY = 64;
    CGFloat tabBarHeight = 49;
    CGFloat heightSearchView = 40;
    CGFloat widthCategory = self.view.bounds.size.width/3;
    
    // MARK: - 搜索商品
    self.viewSearch = [[UIView alloc] initWithFrame:CGRectMake(0, navigationBarY, self.view.bounds.size.width, heightSearchView)];
    self.viewSearch.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.viewSearch];
    
    // MARK: - 左侧商品分类视图 UITableView
    self.tableViewCategory = [[UITableView alloc] initWithFrame:CGRectMake(0, navigationBarY+heightSearchView, widthCategory, self.view.bounds.size.height-heightSearchView-tabBarHeight-navigationBarY)];
    [self.view addSubview:self.tableViewCategory];
    
    self.tableViewCategory.delegate = self;
    self.tableViewCategory.dataSource = self;
    
    [self.tableViewCategory registerClass:[WhzPDDSearchCategoryCell class] forCellReuseIdentifier:KCELLCATEGORY];
    
    self.tableViewCategory.rowHeight = 60;
    
    // MARK: - 右侧商品实物图 UICollectionView
    WhzPDDFlowLayout *flowLayout = [[WhzPDDFlowLayout alloc] init];
    self.collectionViewGoods = [[UICollectionView alloc] initWithFrame:CGRectMake(self.tableViewCategory.bounds.size.width, navigationBarY+heightSearchView, self.view.bounds.size.width-self.tableViewCategory.bounds.size.width, self.tableViewCategory.bounds.size.height) collectionViewLayout:flowLayout];
    self.collectionViewGoods.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionViewGoods];
    
    self.collectionViewGoods.delegate = self;
    self.collectionViewGoods.dataSource = self;
    
    [self.collectionViewGoods registerClass:[WhzPDDSearchGoodsCell class] forCellWithReuseIdentifier:KCELLGOODS];
    [self.collectionViewGoods registerClass:[WhzPDDSearchCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KREUSABLEVIEW];
    
}

#pragma mark - 代理方法 UITableView
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.tableViewCategory) {
        
        [self.collectionViewGoods scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.item] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        
        // 组头偏移量
        CGPoint offset = self.collectionViewGoods.contentOffset;
        offset.y -= 60;
        self.collectionViewGoods.contentOffset = offset;
    }
}

#pragma mark - 代理方法 UICollectionView
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//
//    return CGSizeMake(collectionView.bounds.size.width, 60);
//}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    WhzPDDSearchCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KREUSABLEVIEW forIndexPath:indexPath];
    
    headerView.indexPathForSection = indexPath.section;
    headerView.rootModel = _arrayRoodModel;
    
    return headerView;
}

// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    static float lastOffsetY = 0;
    
    
    if (self.collectionViewGoods == scrollView) {
        
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

// CollectionView分区标题展示结束
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath {
    
    // 当前CollectionView滚动的方向向下，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (_isScrollDown && collectionView.dragging) {
        
        [self selectRowAtIndexPath:indexPath.section + 1];
        
    }else{
        
        [self selectRowAtIndexPath:indexPath.section - 1];
    }
}

// 当拖动CollectionView的时候，处理TableView
- (void)selectRowAtIndexPath:(NSInteger)index {
    
    [self.tableViewCategory selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    
}

#pragma mark - 数据源方法 UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return _arrayRoodModel.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return [_arrayRootData[section][@"children"] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WhzPDDSearchGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KCELLGOODS forIndexPath:indexPath];
    
    cell.indexPathForRow = indexPath.row;
    cell.indexPathForSection = indexPath.section;
    cell.rootModel = _arrayRoodModel;
    
    return cell;
}

#pragma mark - 数据源方法 UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _arrayRootData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WhzPDDSearchCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:KCELLCATEGORY forIndexPath:indexPath];
    
    //    cell.arrayRoot = _arrayRootData;
    cell.indexPathForRow = indexPath.row;
    cell.arrayRootModel = _arrayRoodModel;
    
    return cell;
}

#pragma mark - 网络请求数据
/**
 网络请求
 */
- (void)loadNetworkData {
    
    [[NetworkTool sharedTool] GETWithURLString:@"http://api-static.yangkeduo.com/operations" parameters:nil success:^(NSArray *responseObject) {
        
        _arrayRootData = responseObject;
        _arrayRoodModel = [NSArray yy_modelArrayWithClass:[WhzPDDRootModel class] json:_arrayRootData];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self.tableViewCategory reloadData];
            [self.collectionViewGoods reloadData];
        }];
        
    } failed:^(NSError *error) {
        
        NSLog(@"请求失败%@",error);
        
    }];
}

@end
